/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package resource;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.commons.io.FileUtils;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import javax.activation.MimetypesFileTypeMap; 
import javax.ws.rs.core.Response;

/**
 *
 * @author root
 */
@Path("upload")
public class UploadImageResource {

    private static final String ARTICLE_IMAGES_PATH = "/home/chenyu/image/";
    private static final String JPG_CONTENT_TYPE = "image/jpeg";
    private static final String PNG_CONTENT_TYPE = "image/png";
 
    
    @POST
    @Path("uploadimage2")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadimage2(FormDataMultiPart form, @Context HttpServletResponse response) throws UnsupportedEncodingException {
        System.out.println("" + "2222222222222");
        //获取文件流  
        FormDataBodyPart filePart = form.getField("file");
        //获取表单的其他数据  
        FormDataBodyPart usernamePart = form.getField("username");

        //把表单内容转换成流  
        InputStream fileInputStream = filePart.getValueAs(InputStream.class);

        FormDataContentDisposition formDataContentDisposition = filePart.getFormDataContentDisposition();

        String source = formDataContentDisposition.getFileName();
        String result = new String(source.getBytes("ISO8859-1"), "UTF-8");

        //MD5 文件名
        result = util.Util.hashKeyForDisk(result);
        System.out.println("formDataContentDisposition.getFileName()result " + result);

        String filePath = ARTICLE_IMAGES_PATH + result;
        File file = new File(filePath);
        try {
            //保存文件  
            FileUtils.copyInputStreamToFile(fileInputStream, file);
        } catch (IOException ex) {
        }
        response.setCharacterEncoding("UTF-8");
//        return "images/" + result;
        return Response.ok(source + " uploaded successfully !!").build();
    }

}
